<template>
  <SkeletonLoading v-if="initLoading" />
  <view class="total-module" v-else>
    <CardWrap title="营收数据汇总" style="margin-top: 0">
      <ve-line color="#DADBDD" style="width: 100%" />
      <dataStaticstis :amount="briefReportlistamount" />
    </CardWrap>
    <CardWrap title="收益趋势图">
      <template #extra>
        <span @click="handleClick('income')" class="btn">统计说明</span>
      </template>
      <view class="btns-view">
        <view class="btns-view__item" v-if="dayNum > 0 && incomeEchartData.length">
          <ve-icon name="landscape" size="24" class="btns-view__item-icon" />
          <text class="btns-view__item-text" @click="handelLandscape('income')">横屏查看</text>
        </view>
        <remote-select
          class="btns-view__item"
          :class="{ active: itemNameList.length }"
          type="dict"
          title="选择费项"
          :outData="dict.incomeItemEnums"
          multiple
          :slotStatus="true"
          v-model="itemNameList"
          @change="onChangeItemNameList"
        >
          <template #remote-select>
            <view class="items-center">
              <ve-icon v-if="itemNameList.length" name="filterwhite" size="24" class="btns-view__item-icon" />
              <ve-icon v-else name="filtergray" size="24" class="btns-view__item-icon" />
              <text class="btns-view__item-text">{{ itemNameList.length ? '已选费项' : '全部费项' }}</text>
              <view class="badge" v-show="itemNameList.length">{{ `+${itemNameList.length}` }}</view>
            </view>
          </template>
        </remote-select>
      </view>
      <!-- 收益图饼状图 -->
      <RevenueChart.PieChart v-if="dayNum === 0" :echartData="incomeEchartData[0]" />
      <!-- 收益趋势图 -->
      <RevenueChart.PortraitChart v-else :echartData="incomeEchartData" @getShawBarInfo="getShawBarInfo($event, 'income')" />
    </CardWrap>

    <CardWrap title="门店收益图">
      <template #extra>
        <span @click="handleClick('store')" class="btn">统计说明</span>
      </template>
      <view class="btns-view">
        <view class="btns-view__item" v-if="dayNum > 0 && siteIncomeEchartData.length">
          <ve-icon name="landscape" size="24" class="btns-view__item-icon" />
          <text class="btns-view__item-text" @click="handelLandscape('store')">横屏查看</text>
        </view>
      </view>
      <!-- 收益图饼状图 -->
      <RevenueChart.PieChart v-if="dayNum === 0" :echartData="siteIncomeEchartData[0]" />
      <!-- 门店收益图 -->
      <StoreChart.PortraitChart v-else :echartData="siteIncomeEchartData" @getShawBarInfo="getShawBarInfo($event, 'siteIncome')" />
    </CardWrap>
    <dataModal :data="modalData" :cellList="cellList" v-model:model-value="popupValue" @changeDate="changeDate" />
    <!-- 统计说明 -->
    <ve-modal title="统计说明" v-model:model-value="statisticsVisable" @confirm="statisticsVisable = false" :showCancel="false">
      <view class="statistics-content" v-for="(item, index) in statisticsContent" :key="index">
        {{ item }}
      </view>
    </ve-modal>
  </view>
</template>
<script setup>
  import { ref } from 'vue'
  import dayjs from 'dayjs'
  import { briefReportlist, incomeStatistics, siteIncome } from '@/api/home/revenue'
  import dataStaticstis from '../components/dataStaticstis.vue'
  import CardWrap from '../components/card/card-wrap.vue'
  import dataModal from '../components/data-modal.vue'
  import SkeletonLoading from '../components/skeleton-loading.vue'
  import RevenueChart from '../components/echarts/revenue'
  import StoreChart from '../components/echarts/store'
  import { usePageDict } from '@/hooks/useDict'
  import { useNavigate } from '../components/echarts/utils'
  import { formatNumber } from '@/utils'
  const dict = usePageDict('revenueSummary')

  const { navigateTo } = useNavigate()
  // 切换横屏
  const handelLandscape = (type) => {
    navigateTo({
      chartType: type == 'income' ? 'revenue' : 'store',
      echartData: type == 'income' ? incomeEchartData.value : siteIncomeEchartData.value,
    })
  }

  const props = defineProps({
    refreshUpdateTime: {
      type: Function,
      default: () => {},
    },
  })
  const popupValue = ref(false)
  const modalData = ref({})
  const cellList = ref([
    {
      label: '总收益',
      value: 0,
    },
    {
      label: '总收入',
      value: 0,
    },
    {
      label: '总支出',
      value: 0,
    },
  ])
  const chartDataSource = ref()
  // 切换日期
  const changeDate = (type) => {
    let num = Number(modalData.value.index)
    if (type == 'prev') {
      modalData.value = Object.assign(chartDataSource.value[num - 1], {
        index: num - 1,
        maxLength: chartDataSource.value.length - 1,
      })
    } else if (type == 'next') {
      modalData.value = Object.assign(chartDataSource.value[num + 1], {
        index: num + 1,
        maxLength: chartDataSource.value.length - 1,
      })
    }
    cellList.value[0].value = formatNumber(modalData.value.totalProfitAmount)
    cellList.value[1].value = formatNumber(modalData.value.totalRevenueAmount)
    cellList.value[2].value = formatNumber(modalData.value.totalExpenditureAmount)
  }
  // 获取数据
  const getShawBarInfo = (e, type) => {
    chartDataSource.value = type == 'income' ? incomeEchartData.value : siteIncomeEchartData.value
    modalData.value = Object.assign(chartDataSource.value[e.clickIndex], {
      index: e.clickIndex,
      maxLength: chartDataSource.value.length - 1,
    })
    cellList.value[0].value = formatNumber(modalData.value.totalProfitAmount)
    cellList.value[1].value = formatNumber(modalData.value.totalRevenueAmount)
    cellList.value[2].value = formatNumber(modalData.value.totalExpenditureAmount)
    popupValue.value = true
  }
  // 获取筛选数据
  const dayNum = ref(0)
  const itemNameList = ref([])
  const onChangeItemNameList = () => {
    queryItemNameList()
  }
  const incomeEchartData = ref([])
  const siteIncomeEchartData = ref([])
  const briefReportlistamount = ref({})
  const initLoading = ref(true)
  // 接口参数
  const queryParam = ref({})
  const loadData = (params = {}) => {
    if (params.startTime && params.endTime) {
      let { startTime, endTime } = params
      dayNum.value = dayjs(endTime).diff(dayjs(startTime), 'day')
    }
    queryParam.value = {
      siteIdList: params.siteIdList,
      orderTimeQueryType: params.orderTimeQueryType,
      startTime: params.startTime,
      endTime: params.endTime,
      selectDateType: params.selectDateType,
    }
    briefReportlist(queryParam.value).then((res) => {
      briefReportlistamount.value = res.result || {}
      // 更新数据更新时间
      props.refreshUpdateTime(res.result.lastUpdateTime)
      initLoading.value = false
      uni.hideLoading()
    })
    queryItemNameList()

    siteIncomeEchartData.value = []
    siteIncome(queryParam.value).then((res) => {
      siteIncomeEchartData.value = res.result.data || []
    })
  }
  const queryItemNameList = () => {
    incomeEchartData.value = []
    incomeStatistics({ ...queryParam.value, itemNameList: itemNameList.value }).then((res) => {
      incomeEchartData.value = res.result.data || []
    })
  }
  const statisticsVisable = ref(false)
  const statisticsContent = ref([])
  const handleClick = (type) => {
    let content = [
      '1. 最多展示90天数据，如有需要可更精准的筛选时间',
      '2. 根据订单的取值时间（取车或还车），统计订单下包含的所有费用以及结算情况，如根据实际还车时间筛选订单，则将订单所有费用统计在实际还车这一天',
    ]
    if (type == 'income') {
      content = content.concat([
        '3. 该图表不包含车辆购置费及购置补充费（购置税、过户费、运输费、保证金、手续费）',
        '4. 此处不展示部门的收益趋势，因为部门当前仅用于运营成本，全部为支出',
      ])
    } else {
      content = content.concat(['3.此处不展示部门的收益趋势，因为部门当前仅用于运营成本，全部为支出'])
    }
    statisticsVisable.value = true
    statisticsContent.value = content
  }

  defineExpose({
    loadData,
  })
</script>
<style lang="less" scoped>
  .total-module {
    overflow-x: hidden;
    padding-bottom: 50rpx;
  }
  .btn {
    font-weight: 400;
    font-size: 24rpx;
    color: #3072f6;
    line-height: 34rpx;
  }
  .btns-view {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10rpx;
    &__item {
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2rpx solid #dadbdd;
      border-radius: 4px;
      font-weight: 400;
      font-size: 24rpx;
      color: #8491a8;
      padding: 8rpx 0;
      &-icon {
        margin-right: 8rpx;
      }
      .badge {
        height: 24rpx;
        line-height: 24rpx;
        font-size: 24rpx;
        margin-left: 8rpx;
        padding: 0 8rpx;
        color: #3072f6;
        background: #ffffff;
        border-radius: 12rpx 12rpx 12rpx 12rpx;
      }
    }
  }
  .active {
    border-color: #3072f6;
    color: #fff;
    background: #3072f6;
    .btns-view__item-icon {
      color: #fff;
    }
  }
  .items-center {
    display: flex;
    align-items: center;
  }
  .statistics-content {
    font-size: 28rpx;
    margin-bottom: 20rpx;
  }
</style>
